package controller

import (
	"express/internal/model"
	"express/internal/service"
	"express/pkg/app"
	"github.com/gin-gonic/gin"
	"log"
	"strconv"
)

type UserController struct {
}

func NewUserController() *UserController {
	return &UserController{}
}

func (u *UserController) Login(c *gin.Context) {
	var param model.LoginParam
	c.ShouldBind(&param)
	userService := service.NewUserService()
	ok, err := userService.CheckPassByPhone(param.Phone, param.Pass)
	if err != nil {
		c.JSON(403, gin.H{"msg": "用户不存在"})
	}
	if ok {
		app.Success(c, "")
	} else {
		c.JSON(403, gin.H{"msg": "用户名或密码错误"})
	}
}

func (u *UserController) Register(c *gin.Context) {
	var param model.RegisterParam
	c.ShouldBind(&param)
	userService := service.NewUserService()
	ok, err := userService.CheckPhone(param.Phone)
	if err != nil {
		log.Println(err)
	}
	if !ok {
		c.JSON(403, gin.H{"msg": "密码错误"})
		return
	}

	passhash := app.HashAndSalt([]byte(param.Pass))

	id, _ := app.GenerateID()

	err = userService.AddUser(param.Phone, param.Nickname, passhash, id)
	if err != nil {
		log.Println(err)
	}
	app.Success(c, "")
}

func (u *UserController) GetIdentifier(c *gin.Context) {
	phone := c.Query("phone")
	userService := service.NewUserService()
	id := userService.GetIdentifier(phone)

	png, _ := app.CreatePNG(strconv.FormatInt(id, 10), 200)
	app.Success(c, png)
}

func (u *UserController) GetUserInfo(c *gin.Context) {
	phone := c.Query("phone")
	userService := service.NewUserService()
	user := userService.GetUserByPhone(phone)

	app.Success(c, user)

}
